import {useEffect, useRef, useState} from "react";

export const isFalsy = (value: unknown) => (value === 0 ? false : !value)
export const isVoid = (value: unknown) => value === undefined || value === null || value === ''
//清除多余key：value
export const cleanObject = (object: { [key: string]: unknown }) => {
    const result = {...object};
    Object.keys(result).forEach((key) => {
        const value = result[key];
        if (isVoid(value)) {
            delete result[key];
        }
    });
    return result;
};
//项目初始化
export const useMount = (callback: () => void) => {
    useEffect(() => {
        callback()
        // TODO 依赖项理加上callback会造成无限循环，这个和useCallback以及useMemo有关系
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
}
//防抖
export const useDebounce = <T>(value: T, delay?: number) => {
    const [debouncedValue, setDebounceValue] = useState(value)
    useEffect(() => {
        const timeout = setTimeout(() => setDebounceValue(value), delay);
        return () => clearTimeout(timeout)
    }, [value, delay])
    return debouncedValue;
}

// const aa = <T>(value: T): T => {
//     return value
// }
// const aa1 = (value: number): string => {
//     return Number().toString(value)
// }

export const useDocumentTitle = (title: string, keepOnUnmount = true) => {
    const oldTitle = useRef(document.title).current
    //页面加载时:旧 title
    // 加载后:新 title
    useEffect(() => {
        document.title = title
    }, [title])

    useEffect(() => {
        return () => {
            if (!keepOnUnmount) {
                //如果不指定依赖（不指定监听的谁）,读到的就是旧title
                document.title = oldTitle
            }
        }
    }, [keepOnUnmount, oldTitle])

}

// 重置路由
export const resetRouter = () => window.location.href = window.location.origin

export const subset = <D extends { [Key in string]: unknown },
    K extends keyof D>(
    obj: D,
    keys: K[]
) => {
    const filteredEntries = Object.entries(obj).filter(([key]) =>
        keys.includes(key as K)
    );
    return Object.fromEntries(filteredEntries) as Pick<D, K>
}
/**
 * 返回组件的挂载状态,如何还没加载或者已经卸载,返回false;反之返回true
 */
export const useMountedRef = () => {
    const mountedRef = useRef(false)
    useEffect(() => {
        mountedRef.current = true
        return () => {
            mountedRef.current = false
        }
    })
    return mountedRef
}
